package classroom;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import applicationDAO.InstituteDAO;

import com.project.trac.R;

import core.modules.DatabaseConnector;

public class MessageBoard extends InstituteDAO {


	public static ListFragment newInstance(Context context) {
		MessageBoard lf = new MessageBoard();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.generic_list_a, null);

		new AsynchronousTask().execute();
		return root;
	}

	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ProgressDialog progressDialog;
		ListAdapter listAdapter;

		int rowCount;

		ResultSet rs;

		String KEY_TITLE = "k1";
		String KEY_FID = "k2";
		String KEY_STAMP = "k3";

		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setTitle("Please Wait");
			progressDialog.setMessage("Fetching forum topics...");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {

			try {

				rs = DatabaseConnector.getStatement().executeQuery(
						"SELECT * FROM messaging WHERE catalogId  = " + getSubjectID() + " AND isThread = 1");

				while (rs.next()) {
					// try to sort according to most recent in timestamp
					m = new HashMap<String, String>();
					m.put(KEY_TITLE, rs.getString("title"));
					m.put(KEY_STAMP, rs.getString("dateposted"));
					arrayList.add(m);
				}

				rowCount = rs.last() ? rs.getRow() : 0;

			} catch (SQLException e) {
				System.out.println("doInBackground: ** SQLException ** ");
				System.err.println(e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {

			TextView msg = new TextView(getActivity());
			
			if (rowCount == 0) {
				msg.setText("No forum topics found.");
			} else if (rowCount == 1) {
				msg.setText("Returned " + rowCount + " topic.");
			} else if (rowCount > 1) {
				msg.setText("Returned " + rowCount + " topics.");
			}

			msg.setTextAppearance(getActivity(), R.style.alert_message);
			msg.setGravity(Gravity.CENTER_HORIZONTAL);

			new AlertDialog.Builder(getActivity())
			.setTitle("Information")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setView(msg)
			.setCancelable(false)
			.setPositiveButton(android.R.string.ok, 
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss();
				}
			}).create().show();

			progressDialog.dismiss();

			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					listAdapter = new SimpleAdapter(getActivity(), arrayList,
							R.layout.row_detail_forum, new String[] { KEY_TITLE,
						KEY_STAMP, KEY_FID }, new int[] {
						R.id.forum_text_title,
						R.id.forum_text_stamp });

					setListAdapter(listAdapter);
				}
			});
		}
	} 

	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}

}